import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import axios from "axios";

const SnakeFortune = () => {
  const { state } = useLocation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [fortuneData, setFortuneData] = useState({
    fortune: "",
    career: "",
    love: "",
    taboo: "",
  });
  const [visibleSections, setVisibleSections] = useState({
    fortune: false,
    career: false,
    love: false,
    taboo: false,
  });
  const [error, setError] = useState(null);

  const { name, gender, birthYear, birthMonth, birthDay, birthHour } = state || {};

  useEffect(() => {
    if (!state) return;

    let isMounted = true;
    let requestTimeout = null;

    const fetchFortune = async () => {
      if (!isMounted) return;
      try {
        // 规范化参数
        const normalizedData = {
          name: String(name || "").trim(),
          gender: String(gender || "").trim(),
          birthYear: String(birthYear || "").trim(),
          birthMonth: String(birthMonth || "").trim(),
          birthDay: String(birthDay || "").trim(),
          birthHour: birthHour ? String(birthHour).trim() : "未知",
          type: "近期事件",
        };

        console.log(`Sending request to /api/ask at ${new Date().toISOString()} with data:`, normalizedData);

        if (!normalizedData.name || !normalizedData.gender || !normalizedData.birthYear || !normalizedData.birthMonth || !normalizedData.birthDay) {
          throw new Error("请提供完整的个人信息");
        }

        setLoading(true);
        const response = await axios.post("http://localhost:5000/api/ask", normalizedData);

        console.log("Full API response:", response.data);

        if (response.data.error) {
          throw new Error(`${response.data.error}${response.data.details ? `: ${response.data.details}` : ""}`);
        }

        const result = response.data.answer;
        console.log("Raw AI response:", result);

        const sections = result.split("###").map((section) => section.trim()).filter(Boolean);
        const fortuneSection = sections.find((s) => s.startsWith("近期事件"))?.replace("近期事件", "") || "暂无近期事件数据。";
        const careerSection = sections.find((s) => s.startsWith("运势趋势"))?.replace("运势趋势", "") || "暂无运势趋势数据。";
        const loveSection = sections.find((s) => s.startsWith("建议与禁忌"))?.replace("建议与禁忌", "") || "暂无建议与禁忌数据。";
        const tabooSection = loveSection;

        setFortuneData({
          fortune: fortuneSection,
          career: careerSection,
          love: loveSection,
          taboo: tabooSection,
        });

        setLoading(false);
        setTimeout(() => isMounted && setVisibleSections((prev) => ({ ...prev, fortune: true })), 500);
        setTimeout(() => isMounted && setVisibleSections((prev) => ({ ...prev, career: true })), 1000);
        setTimeout(() => isMounted && setVisibleSections((prev) => ({ ...prev, love: true })), 1500);
        setTimeout(() => isMounted && setVisibleSections((prev) => ({ ...prev, taboo: true })), 2000);
      } catch (error) {
        console.error("Error fetching fortune:", error);
        setError(error.message);
        setFortuneData({
          fortune: "获取运势失败，请稍后重试。",
          career: "获取事业运势失败，请稍后重试。",
          love: "获取姻缘运势失败，请稍后重试。",
          taboo: "获取禁忌建议失败，请稍后重试。",
        });
        setLoading(false);
      }
    };

    requestTimeout = setTimeout(fetchFortune, 300);

    return () => {
      isMounted = false;
      if (requestTimeout) clearTimeout(requestTimeout);
    };
  }, [state]);

  const extractSeason = (text, season) => {
    try {
      const parts = text.split(season);
      if (parts.length > 1) {
        return parts[1].split("。")[0] || `${season}暂无具体数据。`;
      }
      return text.split("。")[0] || `${season}暂无具体数据。`;
    } catch {
      return `${season}暂无具体数据。`;
    }
  };

  if (!state) {
    return (
      <div style={{ width: "600px", margin: "0 auto", padding: "20px", backgroundColor: "#252761", minHeight: "100vh", textAlign: "center" }}>
        <h2 style={{ color: "#ff4d4f" }}>错误</h2>
        <p style={{ color: "#fff" }}>无法获取测算结果，请返回重试。</p>
        <button
          onClick={() => navigate("/snake")}
          style={{ padding: "10px 20px", backgroundColor: "#ff4d4f", color: "#fff", border: "none", borderRadius: "5px", cursor: "pointer" }}
        >
          返回
        </button>
      </div>
    );
  }

  return (
    <div style={{ width: "600px", margin: "0 auto", padding: "20px", backgroundColor: "#252761", minHeight: "100vh", position: "relative" }}>
      <div
        style={{
          backgroundColor: "#ff4d4f",
          color: "#fff",
          fontSize: "24px",
          fontWeight: "bold",
          textAlign: "center",
          padding: "10px 0",
          borderRadius: "5px",
          marginBottom: "20px",
        }}
      >
        2025年蛇年运势测算结果
      </div>
      <div
        style={{
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          border: "2px solid #ff4d4f",
          borderRadius: "10px",
          padding: "15px",
          marginBottom: "20px",
          boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
        }}
      >
        <p style={{ margin: "5px 0", fontSize: "16px", color: "#333" }}>
          <strong>姓名：</strong>
          {name}
        </p>
        <p style={{ margin: "5px 0", fontSize: "16px", color: "#333" }}>
          <strong>性别：</strong>
          {gender === "male" ? "男" : "女"}
        </p>
        <p style={{ margin: "5px 0", fontSize: "16px", color: "#333" }}>
          <strong>生辰：</strong>
          {birthYear}年{birthMonth}月{birthDay}日 {birthHour || "未知"}
        </p>
      </div>
      {error && (
        <div style={{ textAlign: "center", fontSize: "16px", color: "#ff4d4f", marginBottom: "20px" }}>
          错误：{error}
        </div>
      )}
      {loading && (
        <div style={{ textAlign: "center", fontSize: "16px", color: "#fff", marginBottom: "20px" }}>
          正在为您生成运势，请稍候...
        </div>
      )}
      {visibleSections.fortune && (
        <div
          style={{
            backgroundColor: "rgba(255, 255, 255, 0.9)",
            border: "2px solid #ff4d4f",
            borderRadius: "10px",
            padding: "15px",
            marginBottom: "20px",
            boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
            animation: "fadeIn 0.5s ease-in",
          }}
        >
          <h3 style={{ color: "#ff4d4f", fontSize: "20px", marginBottom: "10px" }}>近期事件</h3>
          <p style={{ fontSize: "16px", color: "#333", lineHeight: "1.6" }}>
            <strong>第一个月：</strong> {extractSeason(fortuneData.fortune, "第一个月")}
            <br />
            <strong>第二个月：</strong> {extractSeason(fortuneData.fortune, "第二个月")}
            <br />
            <strong>第三个月：</strong> {extractSeason(fortuneData.fortune, "第三个月")}
          </p>
        </div>
      )}
      {visibleSections.career && (
        <div
          style={{
            backgroundColor: "rgba(255, 255, 255, 0.9)",
            border: "2px solid #ff4d4f",
            borderRadius: "10px",
            padding: "15px",
            marginBottom: "20px",
            boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
            animation: "fadeIn 0.5s ease-in",
          }}
        >
          <h3 style={{ color: "#ff4d4f", fontSize: "20px", marginBottom: "10px" }}>运势趋势</h3>
          <p style={{ fontSize: "16px", color: "#333", lineHeight: "1.6" }}>{fortuneData.career}</p>
        </div>
      )}
      {visibleSections.love && (
        <div
          style={{
            backgroundColor: "rgba(255, 255, 255, 0.9)",
            border: "2px solid #ff4d4f",
            borderRadius: "10px",
            padding: "15px",
            marginBottom: "20px",
            boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
            animation: "fadeIn 0.5s ease-in",
          }}
        >
          <h3 style={{ color: "#ff4d4f", fontSize: "20px", marginBottom: "10px" }}>建议与禁忌</h3>
          <p style={{ fontSize: "16px", color: "#333", lineHeight: "1.6" }}>{fortuneData.love}</p>
        </div>
      )}
      {visibleSections.taboo && (
        <div
          style={{
            backgroundColor: "rgba(255, 255, 255, 0.9)",
            border: "2px solid #ff4d4f",
            borderRadius: "10px",
            padding: "15px",
            marginBottom: "20px",
            boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
            animation: "fadeIn 0.5s ease-in",
          }}
        >
          <h3 style={{ color: "#ff4d4f", fontSize: "20px", marginBottom: "10px" }}>附加建议</h3>
          <p style={{ fontSize: "16px", color: "#333", lineHeight: "1.6" }}>{fortuneData.taboo}</p>
        </div>
      )}
      <div style={{ textAlign: "center", marginTop: "20px" }}>
        <button
          onClick={() => navigate("/snake")}
          style={{
            padding: "10px 20px",
            backgroundColor: "#ff4d4f",
            color: "#fff",
            border: "none",
            borderRadius: "5px",
            cursor: "pointer",
            fontSize: "16px",
          }}
        >
          返回重新测算
        </button>
      </div>
    </div>
  );
};

const styles = `
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
`;

const styleSheet = document.createElement("style");
styleSheet.type = "text/css";
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);

export default SnakeFortune;